﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interactivity;
using System.Windows.Media;


namespace TheOliver.Controls
{


    /// <summary>
    /// Simple action to play a sound.
    /// </summary>
    [DefaultTrigger(typeof(ButtonBase), typeof(System.Windows.Interactivity.EventTrigger), new object[] { "Click" }),
        DefaultTrigger(typeof(UIElement), typeof(System.Windows.Interactivity.EventTrigger), new object[] { "MouseLeftButtonDown" })]
    public class PlaySound : TriggerAction<FrameworkElement>
    {

        /// <summary>
        /// 
        /// </summary>
        public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(Uri), typeof(PlaySound), new PropertyMetadata(null));

        /// <summary>
        /// URI to the media element which is to be played.
        /// </summary>
        public Uri Source
        {
            get { return (Uri)this.GetValue(PlaySound.SourceProperty); }
            set { this.SetValue(PlaySound.SourceProperty, value); }
        }

        /// <summary>
        /// Plays the sound.
        /// </summary>
        /// <param name="args"></param>
        protected override void Invoke(object args)
        {


            Panel panel = this.Panel;
            if (panel != null)
            {
                MediaElement element = new MediaElement();
                element.Source = this.Source;
                element.MediaEnded += delegate
                {
                    panel.Children.Remove(element);
                };

                element.MediaFailed += delegate
                {
                    panel.Children.Remove(element);
                };

                panel.Children.Add(element);
            }


        }

        private Panel Panel
        {
            get
            {
                FrameworkElement parent = this.AssociatedObject as FrameworkElement;
                while (parent != null)
                {
                    if (parent is Grid || parent is Canvas)
                        return (Panel)parent;

                    parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
                }
                return null;
            }
        }

    }
}
